package cn.bavelee.pokeinstaller;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;

/**
 * Created by Bave on 2018/2/2.
 */

public class PokeInstaller {
    public static boolean install(String apkPath) {
        return install(apkPath, null);
    }

    public static boolean install(String apkPath, ShellUtils.Result result) {
        return ShellUtils.execWithRoot("pm install -r --user 0 \"" + apkPath + "\"", result) == 0;
    }
    public static int writeFile(InputStream is, File file) throws IOException {
        int code = -1;
        OutputStream fos = new FileOutputStream(file);
        byte[] buf = new byte[is.available()];
        while ((code = is.read(buf)) != -1) {
            fos.write(buf);
            fos.flush();
        }
        fos.close();
        is.close();
        return code;
    }
    public static ApkInfo getApkInfo(Context context, String apkSourcePath) {
        if (apkSourcePath == null) return null;
        ApkInfo apkInfo = new ApkInfo(apkSourcePath);
        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(apkSourcePath, PackageManager.GET_ACTIVITIES);
        if (pkgInfo != null) {
            pkgInfo.applicationInfo.sourceDir = apkSourcePath;
            pkgInfo.applicationInfo.publicSourceDir = apkSourcePath;
            apkInfo.setAppName(pm.getApplicationLabel(pkgInfo.applicationInfo).toString());
            apkInfo.setPackageName(pkgInfo.applicationInfo.packageName);
            apkInfo.setVersionName(pkgInfo.versionName);
            apkInfo.setVersionCode(pkgInfo.versionCode);
            apkInfo.setIcon(pkgInfo.applicationInfo.loadIcon(pm));
            try {
                PackageInfo installedPkgInfo = pm.getPackageInfo(apkInfo.getPackageName(), 0);
                apkInfo.setInstalledVersionName(installedPkgInfo.versionName);
                apkInfo.setInstalledVersionCode(installedPkgInfo.versionCode);
                apkInfo.setHasInstalledApp(true);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
                apkInfo.setHasInstalledApp(false);
            }
        }
        return apkInfo;
    }
}
